<?php

namespace app\api\controller\v1;

use app\admin\model\Inventory;
use app\admin\model\Inventoryentry;
use app\admin\model\Material;
use app\admin\model\Materialimage;
use app\admin\model\Matprop;
use app\admin\model\Surface;
use app\admin\model\Userfavorite;
use think\Cache;

class Spot extends Base
{
    //列表
    public function tabulation()
    {
        $map                = [];
        $type               = $this->params['type'] ?? 3;//1新品 2热卖 3全部
        $page               = $this->params['page'] ?? 1;
        $materialCateId     = !empty($this->params['materialCateId']) ? $this->params['materialCateId'] : [];
        $texture            = !empty($this->params['texture']) ? $this->params['texture'] : [];
        $surface            = !empty($this->params['surface']) ? $this->params['surface'] : [];
        $otherMatpop        = !empty($this->params['otherMatpop']) ? $this->params['otherMatpop'] : [];


        $cacheTag       = \config('cache_tag')['v1_spot_tabulation'];
        $cacheKey       = $cacheTag. $this->datacenter . $this->forgid . $page . $type . json_encode($materialCateId) . json_encode($texture) . json_encode($surface) . json_encode($otherMatpop);
        $data           =  Cache::get($cacheKey);


        //组装查询条件-----------------

        //属性集合 优先查询符合条件的库存
        if(!empty($otherMatpop))
        {
            $otherMatpop = explode('#',$otherMatpop);
            if(!empty($otherMatpop))
            {
                $matPop = [];
                foreach ($otherMatpop as $key => $value)
                {
                    $value = explode('@', $value);
                    if (empty($value[0]) || empty($value[1])) {
                        continue; // 如果$value[0]或$value[1]为空，则跳过当前循环
                    }
                    $field = $value[0];
                    $ranvalue = explode('_', $value[1]);

                    if(!empty($ranvalue))
                    {
                        //属性值整合
                        $matPop[]   = [
                            'field'          => $field,
                            'startValue'     => $ranvalue[0],
                            'endValue'       => $ranvalue[1],
                        ];
                    }
                }

                if(!empty($matPop))
                {

                    $matPopCacheName= "matPop".md5(json_encode($matPop)).$this->datacenter . $this->forgid.$cacheKey;

                    foreach ($matPop as $k => $v)
                    {
                        $field                          = $v['field'];

                        //拿到组织数据中心对应的id
                        $smallPopID                     = Matprop::whereIn('forgid',$this->forgids)->where('fk_bdl_bd_datacenter',$this->datacenter)->where('fnumber',$field)->value('id');
                        if(!$smallPopID){continue;}

                        //拿到id 去tk_bdl_bal_inventoryentry查值范围
                        $inventoryentryValue            = Inventoryentry::whereIn('forgid',$this->forgids)
                            ->where('fk_bdl_bd_datacenter',$this->datacenter)
                            ->where('fk_bdl_matpropid',$smallPopID);

                        $res = json_decode(\session($matPopCacheName),true);

                            if(!empty($res))
                            {
                                $res = array_unique($res);
                                $inventoryentryValue = $inventoryentryValue->whereIn('id',$res);
                            }

                            if($v['startValue'] === $v['endValue'])
                            {
                              $inventoryentryValue->where('fk_bdl_matpropvalue',$v['startValue']);
                            }else{
                              $inventoryentryValue->where('fk_bdl_matpropvalue',">=",$v['startValue'])->where('fk_bdl_matpropvalue',"<=",$v['endValue']);
                            }

                            $newIds = $inventoryentryValue->column('id');

                            \session($matPopCacheName,json_encode($newIds));
                    }



                    //合并匹配到的库存id
                    $inventoryIDs                        = json_decode(session($matPopCacheName),true);
                    //组装查询条件
                    $idsStr = implode(',', array_map('intval', $inventoryIDs)); // 将 ID 列表转换为用逗号分隔的字符串

                    //如果未匹配到 直接返回空
                    if(empty($idsStr))
                    {
                        $this->success('请求成功', []);
                    }else{
                        $map['id']             = ['in',$idsStr];
                    }
                }


            }
        }


        //材质
        if(!empty($texture))
        {
            $map['fk_bdl_bd_texturenum'] = ['in',$texture];
        }
        //表面
        if(!empty($surface))
        {
            $map['fk_bdl_bd_surfacenum'] = ['in',$surface];
        }


        //根据类型获取产品
        if($type !== 3 || !empty($materialCateId))
        {
            switch ($type) {
                case 1:
                    $field = 'fk_bdl_isnew';
                    break;
                case 2:
                    $field = 'fk_bdl_ishot';
                    break;
                default:
                    $field = [];
            }

            $materialFnumber = Material::whereIn('forgid',$this->forgids)->where('fk_bdl_bd_datacenter',$this->datacenter)->where('fenable',1);
            if(!empty($field)){$materialFnumber = $materialFnumber->where($field,1);}
            if(!empty($materialCateId)){$materialFnumber->where('fk_bdl_bdgroup',$materialCateId);}


            $materialFnumber = $materialFnumber->column('id');

            if(!empty($materialFnumber))
            {
                $map['fk_bdl_bd_material'] = ['in',$materialFnumber];
            }else{
                $map['fk_bdl_bd_material'] = ['in',''];
            }
        }


        //状态 组织 数据中心
        $map['fenable']                         = '1';
        $map['fk_bdl_bd_datacenter']            = (string)$this->datacenter;
        //组装查询条件-----------------


        if(!$data)
        {
            //现货库存产品
            $data = Inventory::with(['inventoryentryvalue','mateia','surfaceone','textureone'])
                ->where($map)
                ->whereIn('forgid', $this->forgids)
                ->order('id', 'desc')
                ->where('fk_bdl_usableqty', '>', 0)
                ->page($page, $this->pageSize)
                ->whereNotNull('fk_bdl_bd_material')
                ->whereNotNull('fk_bdl_inventoryjsondata')
                ->select()
                ->each(function($item) {
                    $item->show_mes     = $this->getInventoryStatusMessage($item->fk_bdl_usableqty);

                    //表面
//                    $surface        = Surface::where('fnumber',$item['fk_bdl_bd_surface'])->where('forgid','in',$this->forgids)->find();
//                    $surface_id     = $surface['id'];
                    $surface_id     = $item['surfaceone']['id'];
                    $material_id    = $item['mateia']['id'];
                    if(!empty($surface_id) && !empty($material_id))
                    {
                        $find       = Materialimage::where('fk_bdl_bd_surface',$surface_id)->where('fk_bdl_bd_material',$material_id)->find();
                        if(!empty($find))
                        {
                            $item['show_image'] = $find['fk_bdl_imageurl'];
                        }else{
                            $item['show_image'] = $this->getDefaultImage();
                        }
                    }else{
                        $item['show_image'] = $this->getDefaultImage();
                    }
                    




                    $item->show_image   = $item->show_image ? $item->show_image : $this->getDefaultImage();
                    //拿到长宽厚
                    $show = [];
                    foreach ($item->inventoryentryvalue as $key => $val)
                    {
                        if(in_array($val['fnumber'],['bdl_thickness','bdl_width','bdl_length','bdl_refthickness','bdl_materialgrade']))
                        {
                            $show[$val['fnumber']] = $val['pivot']['fk_bdl_matpropvalue'];
                        }
                    }

                    $item->show_matprop = $show;
                });

                Cache::tag($cacheTag)->set($cacheKey,$data,$this->cacheExpire);
        }




        $this->success('请求成功'.count($data), $data);

    }

    //详情
    public function detail()
    {
        $check      = $this->plulicValidate($this->params,
            ['fk_bdl_inventoryid|库存ID'],
            [  'require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }
        $fk_bdl_inventoryid = $this->params['fk_bdl_inventoryid'];

        $cacheTag       = \config('cache_tag')['v1_spot_detail'];
        $cacheKey       = $cacheTag. $this->datacenter . $this->forgid . $fk_bdl_inventoryid;
        $data           =  Cache::get($cacheKey);


        if(!$data)
        {
            //现货库存产品
            $material = Inventory::with(['inventoryentryvalue','mateia','surfaceone','textureone'])
                ->where('id',$fk_bdl_inventoryid)
                ->order('id', 'desc')
                ->find();


//            $surface        = Surface::where('fnumber',$material['fk_bdl_bd_surface'])->where('forgid','in',$this->forgids)->find();
//            $surface_id     = $surface['id'];
            $surface_id     = $material['surfaceone']['id'];

            $material_id    = $material['mateia']['id'];
            if(!empty($surface_id) && !empty($material_id))
            {
                $find       = Materialimage::where('fk_bdl_bd_surface',$surface_id)->where('fk_bdl_bd_material',$material_id)->find();

                if(!empty($find))
                {
                    $show_image = $find['fk_bdl_imageurl'];
                }else{
                    $show_image = $this->getDefaultImage();
                }
            }else{
                $show_image = $this->getDefaultImage();
            }

            //拿到长宽厚
            $show = [];
            foreach ($material->inventoryentryvalue as $key => $val)
            {
                if(in_array($val['fnumber'],['bdl_thickness','bdl_width','bdl_length','bdl_refthickness','bdl_materialgrade']))
                {
                    $show[$val['fnumber']] = $val['pivot']['fk_bdl_matpropvalue'];
                }
            }

            $material->show_matprop = $show;

            if(!empty($material))
            {
                $material['show_mes']           = $this->getInventoryStatusMessage($material['fk_bdl_usableqty']);
                $material['show_image']         = $show_image;
            }

            if(!$this->user_id)
            {
                $material['is_favorite'] = 2;
            }else{
                $isFavrite  = Userfavorite::where(['fk_bdl_userid' => $this->user_id, 'forgid' => $this->forgid,'fk_bdl_bd_datacenter'=>$this->datacenter,'fk_bdl_inventoryid'=>$this->params['fk_bdl_inventoryid']])->find();

                if(!empty($isFavrite))
                {
                    $material['is_favorite'] = 1;
                }else{
                    $material['is_favorite'] = 2;
                }
            }

            $material['detail_img']     = now_domain(). '/static/mini_program/ght.png';


            $data = $material;

            Cache::tag($cacheTag)->set($cacheKey,$data,$this->cacheExpire);
        }

        $this->success('请求成功', [
                'mater'         => $data,
        ]);
    }
}